package com.example.myapplication.utils

import android.app.Activity
import android.app.RecoverableSecurityException
import android.content.ContentUris
import android.content.Context
import android.content.IntentSender.SendIntentException
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast


object FileUtils {
    const val REQUEST_CODE_DELETE_PERMISSION = 10

    /**
     *
     * @param context
     * @param id
     * @return
     */
    fun deleteVideo(context: Context, id: Long): Int {
        try {
            val videoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
            return context.contentResolver.delete(videoUri, null, null)
        } catch (e: SecurityException) {
            handleSecurityException(context, e) // 处理权限异常
        }
        return -1
    }

    private fun handleSecurityException(context: Context, e: SecurityException) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && e is RecoverableSecurityException
        ) {
            val intentSender = e.userAction.actionIntent.intentSender
            try {
                //val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                (context as Activity).startIntentSenderForResult(
                    intentSender,
                    REQUEST_CODE_DELETE_PERMISSION,
                    null,
                    0,
                    0,
                    0,
                    null
                )
            } catch (ex: SendIntentException) {
                throw ex
            }
        } else {
            Log.d("VideoDelete", "删除失败：" + e.message)
            Toast.makeText(context, "删除失败~", Toast.LENGTH_SHORT).show()
        }
    }
}
